package lib;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


import dao.LogDAO;

public class ConnectionWeb {
	
	private URL url;
	public String connect(String url)
	{
		String strHtml = "";
		try {
			URL con= new URL(url);
		
		
			URLConnection cnx = con.openConnection();
			cnx.setAllowUserInteraction(false);         
			cnx.setDoOutput(true);
			cnx.addRequestProperty("User-Agent", 
			    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
			cnx.setConnectTimeout(6000);
			//	cnx.setRequestProperty("Accept","undefined");
				//cnx.addRequestProperty("Accept-Language","vi-vn,vi;q=0.8,en-us;q=0.5,en;q=0.3");
				////cnx.addRequestProperty("Accept-Encoding", "gzip, deflate");
				//cnx.addRequestProperty("Content-Type","application/octet-stream");
				//cnx.addRequestProperty("Accept-Charset", "utf-8");
				//cnx.addRequestProperty("Connection", " 	keep-alive");			
			InputStream is;
			is = cnx.getInputStream();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
			
			while (true)
			{
				String str = br.readLine();
				if (str != null)
					strHtml += str;
				else
					break;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return strHtml;
	}
	public boolean TryConnect(String url)
	{
		String strHtml = "";
		try {
			URL con= new URL(url);
			URLConnection cnx = con.openConnection();
			cnx.setAllowUserInteraction(false);         
			cnx.setDoOutput(true);
			cnx.addRequestProperty("User-Agent", 
			    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
			cnx.setConnectTimeout(6000);
			//	cnx.setRequestProperty("Accept","undefined");
				//cnx.addRequestProperty("Accept-Language","vi-vn,vi;q=0.8,en-us;q=0.5,en;q=0.3");
				////cnx.addRequestProperty("Accept-Encoding", "gzip, deflate");
				//cnx.addRequestProperty("Content-Type","application/octet-stream");
				//cnx.addRequestProperty("Accept-Charset", "utf-8");
				//cnx.addRequestProperty("Connection", " 	keep-alive");			
			InputStream is;
			is = cnx.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
		} catch (IOException e) {
			// TODO Auto-generated catch block	
			e.printStackTrace();
			return false;
		}
		
		
		
		return true;
	}
	
	public Document getInfo(String turl)
	{
		URL con;
		Document t=null;;
		String strHtml=""; 
		try {
		
			con = new URL(turl);
			URLConnection cnx = con.openConnection();
			cnx.setAllowUserInteraction(false);         
			cnx.setDoOutput(true);
			cnx.addRequestProperty("User-Agent", 
			    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
			cnx.setConnectTimeout(6000);
			
			InputStream is = cnx.getInputStream();
			url = cnx.getURL();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
			strHtml = "";
			while (true)
			{
				String str = br.readLine();
				if (str != null)
 					strHtml += str;
				else
					break;
			}
		
			t=Jsoup.parse(strHtml);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//ghi log
			LogDAO.insert("can not load "+turl);
			e.printStackTrace();
		}
		if(strHtml.equals("")||t==null)
		{
			try {
				t= Jsoup.connect(turl)
						  .data("query", "Java")
						  .userAgent("Mozilla")
						  .cookie("auth", "token")
						  .timeout(6000)
						  .post();
				System.out.println("Su dung connect 2");
				url=new URL(turl);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					LogDAO d=new LogDAO();
					d.insert(e1.getMessage());
				}
			return t;
		}
		return t;		
	}
	
	public String getUrl()
	{
		if(url!=null)
		return url.toString();
		
		return null;
	}
	
	public List<Element> executeXpath(Document doc, String xpath,int con)
	{
		if(xpath.equals("null"))
		{
			List<Element> t=new ArrayList<Element>();
			return t;
		}
		if(doc==null) return null;
		int num=xpath.indexOf("$$");
		
		String xp=xpath.substring(0, num);
		List<String> l=getStringName(xp);
		Element e=doc.children().get(0);
		int count=0;
		for(int i=0;i< xp.length();i++)
		{
			if(xp.charAt(i)=='/') count++;
		}
		int count2=0;
		for(int i=1;i<l.size();i++)
		{
			String t=l.get(i);
			String name=this.getNameOfNode(t);
			int n=this.getNumOfNode(t);
			Elements le=e.children();
			int dem=0;
		
			for(int j=0;j<le.size();j++)
			{
				Element te=le.get(j);
				if(te.nodeName().equals(name)) 
				{	
					if(dem==n)
					{
						e=te;
						count2++;
						break;
					}
					else dem++;
				}
			}
			
			
		}
		
		if(e!=null&&getLastName(xp).equals(e.tagName())&&count2==count-1)	
			{
				List<Element> tl=new ArrayList<Element>();
				tl.add(e);
				return tl;
			}
		
		String myxp=xpath.substring(num+2, xpath.length());
		
		List<Element> le2=executeXpath2(doc,myxp,con);
		return le2;
		
	}
	
	private String getLastName(String t)
	{
		int n=t.lastIndexOf("/");
		String s=t.substring(n+1,t.length());
		return s;
	}
	public List<String> getStringName(String t)
	{
		List<String> l= new ArrayList<String>();
		int n1;
		int n2;
		n1=t.indexOf("/");
		n2=0;
		while(n2>=0)
		{
			n2=t.indexOf("/", n1+1);
			l.add(t.substring(n1+1, n2));
			n1=n2;
			n2=t.indexOf("/",n2+1);
		}
		l.add(t.substring(n1+1,t.length()));
		return l;
	}
	
	public int getNumOfNode(String t)
	{
		int dem=0;
		if(t.indexOf("[")==-1) return dem;
		int n1=t.indexOf("[");
		int n2=t.indexOf("]");
		String st=t.substring(n1+1,n2);
		dem=Integer.parseInt(st);
		return dem-1;
	}
	
	public String getNameOfNode(String t)
	{
		if(t.indexOf("[")==-1) return t;
		int n1=t.indexOf("[");
		int n2=t.indexOf("]");
		String st=t.substring(0,n1);
	
		return st;
	}
	
	public List<String> getString(String t)
	{
		List<String> l= new ArrayList<String>();
		int n=t.indexOf('/');
		l.add(t.substring(0,n));
		int m= t.indexOf('/',n+1);
		l.add(t.substring(n+1,t.indexOf('/',n+1)));
		n=t.indexOf('/',n+1);
		l.add(t.substring(n+1, t.length()));
		
		return l;
		
	}
	public String getStringNum(String t,int num)
	{
		if(num<=0) return null;
		
		
	
		int n=t.indexOf('/');
		if(num==1) return t.substring(0,n);
		
		if(num==2) return t.substring(n+1,t.indexOf('/',n+1));
		n=t.indexOf('/',n+1);
		if(num==3) return t.substring(n+1, t.length());
		return null;
		
	}
	public String getStringNum2(String t,int num)
	{
		if(num<=0) return null;
		int count=0;
		for(int i=0;i<t.length();i++)
		{
			if(t.charAt(i)=='/') count++;
		}
		if(count>1)
		{
			List l= new ArrayList();

			List l2= new ArrayList();
			int n1=t.indexOf("\"");
			int n2;
			while(n1>0)
			{
				n2=t.indexOf("\"",n1+1);
				l.add(n1);
				l2.add(n2);
				if(n2==t.length()) break;
				n1=t.indexOf("\"",n2+1);		
			}
			int n=0;
			for(int i=0;i<t.length();i++)
			{
				if(t.charAt(i)=='/')
				{	
					boolean flag= false;
					for(int j=0;j<l.size();j++)
					{
						int c1=(int) l.get(j);
						int c2=(int) l2.get(j);
						
						if(c1<i&&i<c2) 
						{
							flag=true;	
							break;
						}
					}
					
					if(flag==false) 
					{
						n=i;
						break;
					}
				
				}
			}
			
			if(num==1) return t.substring(0,n);
			
			if(num==2) return t.substring(n+1,t.length());
			
		}
		else
		{
			int n=t.indexOf('/');
			if(num==1) return t.substring(0,n);
			
			if(num==2) return t.substring(n+1,t.length());
		}
	
		return null;
		
	}
	public String getName(String t)
	{
		if(t.indexOf(" ")==-1) return t;
		else
			return t.substring(0,t.indexOf(" "));
		
		
	}
	public List<String> getAtt(String t)
	{
		if(t.indexOf(" ")==-1)return null;
		else
		{	
			List<String> l= new ArrayList<String>();
			int n1=t.indexOf(" ");
			int n2=t.indexOf("=");
			
			String a=t.substring(n1, n2);

			while(n2!=-1)
			{
				for(int i= n2;i>0;i--)
				{
					char t2=t.charAt(i);
					if(t2==' ')
						{
							n1=i;
							break;
						}
				}
				l.add(t.substring(n1+1,n2));
				n2=t.indexOf("=",n2+1);
				while(checkChar(n2,t))
				{
					n2=t.indexOf("=",n2+1);
				}
			}
			
			for(int i= 0;i<l.size();i++)
			{
				String tmp=l.get(i);
				if(tmp.indexOf(" ")!=-11)
				{
					tmp=tmp.replace(" ","");
					l.set(i,tmp);
				}
			}
			return l;
		}
	}
	
	public boolean checkChar(int num, String t)
	{
		boolean flag2=false;
		List l= new ArrayList();

		List l2= new ArrayList();
		int n1=t.indexOf("\"");
		int n2;
		while(n1>0)
		{
			n2=t.indexOf("\"",n1+1);
			l.add(n1);
			l2.add(n2);
			if(n2==t.length()) break;
			n1=t.indexOf("\"",n2+1);		
		}
		boolean flag;

		flag= false;
		for(int j=0;j<l.size();j++)
		{
				int c1=(int) l.get(j);
				int c2=(int) l2.get(j);
					
				if(c1<num&&num<c2) 
				{
					flag=true;	
					break;
				}
				
				
		}		
	
		
		return flag;
	}
	
	private List<Element> executeXpath2(Document doc, String xpath,int con)
	{
		xpath=RemoveString(xpath,">");
		xpath=RemoveString(xpath,"<");
		String txp=xpath;
		List<Element> kq= new ArrayList<Element>();
		List<Element> l;
		int count=0;
		for(int i=0;i<xpath.length();i++)
		{
			if(xpath.charAt(i)=='/')
				count++;		
		}
		if(xpath.indexOf("/")!=-1) count++;
	/*	if(count==0)
		{
			l=executeXpath3(node,xpath,con);
			return l;
		}*/
		
		String st=this.getStringNum2(xpath, 1);
		String st2=this.getStringNum2(xpath, 2);
		List<String> l_att;
		l_att=getAtt(st);
		
		
		List<String> lAttValue;
		lAttValue=getAttValue(st);
		st=this.getName(st);
		st2=this.getName(st2);
		
		l=doc.getElementsByTag(st);

		
		if(l_att!=null)
		{
			for(int i=0;i<l_att.size();i++)
			{
				String t=l_att.get(i);
				String t2=lAttValue.get(i);
				int len=l.size();
				int dem= 0;
				while(dem<len)
				{
					Element tam=l.get(dem);
					if(tam.hasAttr(t)==true&&tam.attr(t).equals(t2)==true)
					{
						dem++;
					}
					else
					{	
						l.remove(dem);
						len--;
						
					}
				}
						
			}
		}
		
		int len=l.size();
		int dem= 0;
		if(len==1) return l;
		
		while(dem<len)
		{
			Element tam=l.get(dem);
			if(tam.children().size()!=0)
			{
				Element tam2=tam.children().get(0);
				if(tam2.tagName().equals(st2)==false)
				{
				   l.remove(dem);
				   len--;
				}				
				else
				dem++;
			}
			else
			{  l.remove(dem);
				len--;
			}
		}
		len=l.size();
		dem= 0;
		if(len==1) return l;
		while(dem<len)
		{
			Element tam=l.get(dem);
			List<Element> l_t=tam.children();
			if(l_t.size()<con)
			{
				l.remove(dem);
				len--;
			}
			else
				dem++;
		}
		
		 if(l.size()>1)
		 {
			 //ghi log co nhiu hon 1 node
		 }
		 
		 if(l.size()==0)
		 {
			 l=executeXpath4(doc,txp);
		 }
		 if(l.size()==0)
		 {
			 l=executeXpath5(doc,txp);
		 }
		return l;
		
	}
	public List<Element> executeXpath3(Document node, String xpath,int con)
	{
		List<Element> kq= new ArrayList<Element>();
		List<Element> l;
		List<String> lAtt;
		List<String> lAttValue;
		lAtt=getAtt(xpath);
		lAttValue=getAttValue(xpath);
		String st=this.getName(xpath);
		l=node.getElementsByTag(st);
		
		if(lAtt!=null)
		{
			for(int i=0;i<lAtt.size();i++)
			{
				String t=lAtt.get(i);
				String t2=lAttValue.get(i);
				int len=l.size();
				int dem= 0;
				while(dem<len)
				{
					Element tam=l.get(dem);
					String t3=tam.attr(t);
					if(tam.hasAttr(t)==true&&tam.attr(t).equals(t2)==true)
					{
						dem++;
					
					}
					else
					{
						l.remove(dem);
						len--;
					}
				}
						
			}
		}
		
		return l;
		
	}
	
	public List<Element> executeXpath4(Document node, String xpath)
	{
		List<Element> kq= new ArrayList<Element>();
		List<Element> l;
		List<String> lAtt;
		List<String> lAttValue;
		String st2=this.getStringNum2(xpath, 1);
		lAtt=getAtt(st2);
		
		lAttValue=getAttValue(st2);
		String st=this.getName(xpath);
		l=node.getElementsByTag(st);
		
		if(lAtt!=null)
		{
			for(int i=0;i<lAtt.size();i++)
			{
				String t=lAtt.get(i);
				String t2=lAttValue.get(i);
				int len=l.size();
				int dem= 0;
				while(dem<len)
				{
					Element tam=l.get(dem);
					String t3=tam.attr(t);
					if(tam.hasAttr(t)==true&&tam.attr(t).equals(t2)==true)
					{
						dem++;
					
					}
					else
					{
						l.remove(dem);
						len--;
					}
				}
						
			}
		}
		
		return l;
		
	}
	public List<Element> executeXpath5(Element doc, String xpath)
	{
		String st=this.getStringNum2(xpath, 1);
		String st2=this.getStringNum2(xpath, 2);
		List<String> l_att;
		l_att=getAtt(st);
		
		
		List<String> lAttCon;
		lAttCon=getAtt(st2);
		st=this.getName(st);
		String st2_name=this.getName(st2);
		
		List<Element> l;
		l=doc.getElementsByTag(st);

		
		if(l_att!=null)
		{
			for(int i=0;i<l_att.size();i++)
			{
				String t=l_att.get(i);
				int len=l.size();
				int dem= 0;
				while(dem<len)
				{
					Element tam=l.get(dem);
					if(tam.hasAttr(t)==true)
					{
						dem++;
					}
					else
					{	
						l.remove(dem);
						len--;
						
					}
				}
						
			}
		}
		
		int len=l.size();
		int dem= 0;
		if(len==1) return l;
		while(dem<len)
		{
			Element tam=l.get(dem);
			if(tam.children().size()!=0)
			{
				Element tam2=(Element) tam.children().get(0);
				if(tam2.tagName().equals(st2_name)==false)
				{
				   l.remove(dem);
				   len--;
				}				
				else
				dem++;
			}
			else
			{  l.remove(dem);
				len--;
			}
		}
		
		if(l.size()==1) return l;
		len=l.size();
		dem=0;
		
		if(lAttCon!=null)
		{
			for(int i=0;i<lAttCon.size();i++)
			{
				String t=lAttCon.get(i);
			 len=l.size();
			 dem= 0;
				while(dem<len)
				{
					Element tam=l.get(dem);
					if(tam.children().size()!=0)
					{
						Element tam2=(Element) tam.children().get(0);
						if(tam2.hasAttr(t)==false)
						{
						   l.remove(dem);
						   len--;
						}				
						else
						dem++;
					}
				}
						
			}
		}
		
		
		return l;
		
	}
	
	public List<String> getAttValue(String t)
	{
		if(t.indexOf(" ")==-1)return null;
		else
		{	
			List<String> l= new ArrayList<String>();
			int n1=t.indexOf("\"");
			int n2=t.indexOf("\"",n1+1);
			
			String a=t.substring(n1, n2);

			while(n2!=-1)
			{
				String temp=t.substring(n1+1,n2);
				if(temp==null||temp.equals(""))
				{
					l.add("");
				}
				else{
					l.add(temp);
				}
				if(n2<t.length()-1 ) n1=t.indexOf("\"",n2+1);
				else break;
				if(n1==-1)  break;
				n2=t.indexOf("\"",n1+1);
			}

			return l;
		}
	}
	
	public String RemoveString(String s, String t)
	{
		s=s.replaceAll(t,"");
		return s;
	}
	
	
	public String convertTagNode(Element t)
	{
		return null;
	}
	
	
}
